package org.star.extend;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/6/11 17:16
 * @Description: 手写负载均衡算法 - 随机
 */
public class MyRandomRule10000 extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        // 获取当前请求的服务实例
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        List<Server> servers = loadBalancer.getReachableServers();
        int index = ThreadLocalRandom.current().nextInt(servers.size());

        return servers.get(index);
    }
}
